#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail

if [ $# -lt 1 ]
then
  echo "usage: $0 FEATURE [OPTIONS]"
  exit 1
fi

feature=$1
shift

# We assume that `target` is the normal target directory.
base_target_dir="target"

# Check to see if we have the nightly toolchain installed, and if so, do a deeper check to see if
# there's a custom target directory configured.
cargo +nightly &> /dev/null && rc=$? || rc=$?
if [ $rc -eq 0 ]; then
  overridden_base_target_dir=$(cargo +nightly -Zunstable-options config get | grep "build.target-dir" | sed 's/build.target-dir = //' | sed 's/\"//g' || true)
  if [ ! -z "$overridden_base_target_dir" ]; then
    base_target_dir=$overridden_base_target_dir
  fi
fi

# Make sure that `cargo check` has been run so that we have something to bootstrap our per-feature
# target directory from.
if [ ! -d $base_target_dir/debug ]
then
  echo "$0: Run \`cargo check\` first to prime the \`${base_target_dir}\` directory."
  exit 1
fi

target=$PWD/$base_target_dir/component-features/feature-$feature
mkdir -p $target
log=$target/.logfile
trap 'rm --force --recursive $target' EXIT

cp --archive --link $base_target_dir/debug $target
rm --force $base_target_dir/debug/.cargo-lock

echo "===== Feature: $feature ====="
if cargo check --tests --bin vector \
	--no-default-features \
	--features $feature \
	--target-dir $target \
	"$@" >$log 2>&1
then
  # If the run was successful, just output the `Finished` line
  # to prevent cluttering the logs.
  exit=0
  fgrep --word-regexp Finished $log
else
  exit=$?
  cat $log
fi

exit $exit

# It would be nice to relink newer files back into `target` so
# subsequent runs can pick them up, but that ends up confusing `cargo`
# later in the process.
